package com.idata.model.response;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import com.idata.model.proxyDO.KGCitizenDO;
import com.idata.model.utils.DefaultImgUrlManager;
import com.idata.model.utils.ImgReplaceUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.util.Optional;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class CitizenResponse {
    private String name = "";
    private int age;
    private String nation = "";
    private String education = "";
    private String nativePlace = "";

    private String idCard = "";
    private String avatarUrl = "";
    private String registeredResidenceAddress;
    private String currentAddress;
    private String gender;

    private int disputeTotalCount;

    // 相关人员检索需要
    private String relationName = "";


    public static CitizenResponse convertFromKGCitizen(KGCitizenDO kgCitizenDO) {
        CitizenResponse citizenResponse = new CitizenResponse();
        citizenResponse.setIdCard(kgCitizenDO.getPeople().getIdCard());
        citizenResponse.setName(kgCitizenDO.getPeople().getName());
        citizenResponse.setRegisteredResidenceAddress(kgCitizenDO.getPeople().getRegisteredResidenceAddress());
        citizenResponse.setCurrentAddress(kgCitizenDO.getPeople().getCurrentAddress());
        citizenResponse.setAvatarUrl(kgCitizenDO.getPeople().getAvatarUrl());

        citizenResponse.setAge(Optional.ofNullable(kgCitizenDO.getTag().getAge()).orElse(0));
        citizenResponse.setNation(kgCitizenDO.getTag().getNation());
        citizenResponse.setEducation(kgCitizenDO.getTag().getEducation());
        citizenResponse.setNativePlace(kgCitizenDO.getTag().getNativePlace());
        citizenResponse.setGender(kgCitizenDO.getTag().getGender());

        return citizenResponse;
    }

    public String getAvatarUrl() {
        return StringUtils.isEmpty(avatarUrl) ? DefaultImgUrlManager.DEFAULT_AVATAR_IMG_URL : ImgReplaceUtils.replaceHost(avatarUrl);
    }

    public int getAge() {
        if (age > 0) {
            return age;
        }
        // 接下来 age 都是 <=0 了
        if (StrUtil.isEmpty(idCard)) {
            return age;
        }
        int ageByIdCard = age;
        try {
            ageByIdCard = IdcardUtil.getAgeByIdCard(idCard);
        } catch (Exception ignored) {
        }
        return ageByIdCard;
    }

    public String getGender() {
        if (StrUtil.isNotEmpty(gender)) {
            return gender;
        }
        // 接下来 gender 都是空了
        if (StrUtil.isEmpty(idCard)) {
            return gender;
        }
        String genderByIdCard = gender;
        try {
            genderByIdCard = IdcardUtil.getGenderByIdCard(idCard) == 1 ? "男" : "女";
        } catch (Exception ignored) {
        }
        return genderByIdCard;
    }
}
